package com.llkj.contractmanagement.contractmanagement.contract;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.llkj.contractmanagement.main.BaseActivity;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.contractmanagement.adapter.FileListAdapter;
import com.llkj.contractmanagement.customview.MyDialog;
import com.llkj.contractmanagement.customview.TitleBar;
import com.llkj.contractmanagement.utils.CacheFileUtils;
import com.llkj.contractmanagement.utils.LogUtil;
import com.llkj.contractmanagement.utils.StringUtil;
import com.llkj.contractmanagement.utils.ToastUtil;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import rx.functions.Action1;

/**
 * author: dong.yj
 * created on: 2016/8/18 17:09
 * description:我的下载列表界面
 */
public class FileListActivity extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, MyDialog.ItemClickListener {
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_contractlist;
    }

    @Bind(R.id.title_contractlist)
    TitleBar titleBar;
    @Bind(R.id.lv_contractlist)
    ListView lv_contractlist;
    private FileListAdapter adapter;
    private ArrayList<File> list = new ArrayList<File>();
    private ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    private MyDialog dialog;
    private int delIndex;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        init();
    }

    private void init() {
        initData();
        setListener();
    }

    private void initData() {
        dialog = new MyDialog(FileListActivity.this, "确定要删除吗", R.style.MyDialogStyle1);
        dialog.setItemClickListener(this);
        dialog.setLeftText("取消");
        dialog.setRightText("确定");
        titleBar.setRight_background(null);
        titleBar.setTitle_text("我的下载");
        loadFileList();
        adapter = new FileListAdapter(this, data);
        lv_contractlist.setAdapter(adapter);
    }

    private void loadFileList() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if(aBoolean){
                            getAllFiles(new File(CacheFileUtils.FOLDER_CACHE));
                            getMapData(list);
                        }
                    }
                });

    }


    private void setListener() {
        titleBar.setTopBarClickListener(this);
        lv_contractlist.setOnItemClickListener(this);
        lv_contractlist.setOnItemLongClickListener(this);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = list.get(position).toString();
        File file = new File(path);
        if (file.exists()) {
            String type = path.substring(path.lastIndexOf(".") + 1);
            if (type.equals("pdf")) {
                openPdf(file);
            } else {
                openWord(file);
            }
        }
    }

    private ArrayList<Map<String, Object>> getMapData(ArrayList<File> list) {
        HashMap<String, Object> item;
        int i = 0;
        for (i = 0; i < list.size(); i++) {
            item = new HashMap<String, Object>();
            String path = list.get(i).toString();
            String name = path.substring(path.lastIndexOf("/") + 1, path.length());
            item.put("itemfileName", name);
            item.put("itemfilePath", path);
            data.add(item);
        }
        return data;
    }

    private void getAllFiles(File file) {
        File files[] = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    getAllFiles(f);
                } else {
                    this.list.add(f);
                }
            }
        } else {
            ToastUtil.makeShortText(this, "没有访问权限");
        }
    }

    /**
     * 获取文件并按文件名称排序
     *
     * @param path 初始路径
     * @return
     */
    public static ArrayList<File> getFilesOrder(String path) {
        ArrayList<File> filesList = new ArrayList<File>();
        if (StringUtil.isEmpty(path)) {
            return filesList;
        }
        File file = new File(path);
        if (!file.isDirectory()) {
            return filesList;
        }
        ;
        File[] files = file.listFiles();
        if (files == null) {
            return filesList;
        }
        File temp;
        for (int i = 0; i < files.length; i++) {
            for (int j = 0; j < files.length - i - 1; j++) {
                if (files[j].getName().compareTo(files[j + 1].getName()) > 0) {
                    temp = files[j];
                    files[j] = files[j + 1];
                    files[j + 1] = temp;
                }
            }
        }
        return filesList;
    }

    /*
    * 打开word文件
    * */
    private void openWord(File file) {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/msword");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.makeShortText(this, "No Application Available to View WORD");
        }
    }

    /*
    * 打开pdf文件
    * */
    private void openPdf(File file) {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.makeShortText(this, "No Application Available to View PDF");
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (dialog != null) {
            delIndex = position;
            dialog.show();
        }
        return true;
    }

    @Override
    public void left() {

    }

    @Override
    public void right() {
        String path = list.get(delIndex).toString();
        LogUtil.e("filePosition------>" + delIndex);
        LogUtil.e("fileSize------>" + list.size());
        File del = new File(path);
        if (!del.exists()) {
            return;
        }
        del.delete();
        list.clear();
        data.clear();
        loadFileList();
        adapter.notifyDataSetChanged();
    }
}
